package marketPlace;

import general.ProductPrice;
import general.ProductRecord;
import general.ProductRequest;

import java.sql.Date;
import java.util.PriorityQueue;

import net.jini.core.transaction.Transaction;
import net.jini.core.transaction.Transaction.Created;
import net.jini.core.transaction.TransactionFactory;
import net.jini.core.transaction.server.TransactionManager;
import net.jini.space.JavaSpace;

public class AuctionQueue extends Thread {
	
	public MarketPlace fMarketPlace;
	private JavaSpace fJavaSpace;
	private TransactionManager fTransactionMgr;
	private PriorityQueue<ProductRecord> fQueue;
	
	public AuctionQueue(MarketPlace marketPlace) {
		super();
		fMarketPlace = marketPlace;
		fJavaSpace = fMarketPlace.getSpace();
		fTransactionMgr = fMarketPlace.getTransactionManager();
		fQueue = new PriorityQueue<ProductRecord>();
		this.start();
	}

	public void run() {
		boolean finished;
		while (true) {
			
			// Check whether there is a product that should be auctioned
			finished = false;
			while (!finished) {
				if (!fQueue.isEmpty()) {
					ProductRecord record = fQueue.poll();
					if (record.getAuctionOptions().getStartTime().before(new Date(System.currentTimeMillis()))) {
					
						try {
							// Initialize transaction
							Created created = TransactionFactory.create(fTransactionMgr, 5000);
							Transaction transaction = created.transaction;
				        
					        // Create and write request into space
							ProductRequest productRequest = new ProductRequest(record.getProduct().getId(), record.getAuctionOptions().getEndTime(), new ProductPrice(record.getAuctionOptions().getMinimumPrice()));
					        fJavaSpace.write(productRequest, transaction, 24*60*60);
					        transaction.commit();
					        
					        // Adjust state of product
					        // TODO
					        
					        System.out.println("Product placed in auction space");
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						// Put product back to queue
						fQueue.add(record);
						finished = true;
					}
				} else {
					finished = true;
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void addProductRecord(ProductRecord productRecord) {
		fQueue.add(productRecord);
	}

}
